import { FC, useState, createRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Button, TextField } from '@mui/material';
import logo from '../../assets/logo.png';
import './index.less';

const routes = [
  { path: '/', title: '首页', children: ['/follow', '/latest', '/hot'] },
  { path: '/community', title: '圈子' },
  { path: '/resources', title: '资源' },
  { path: '/opensource', title: '开源' },
];

const Navbar: FC = () => {
  const navList = createRef<HTMLUListElement>();
  // Style of slide-bar
  const [showSlide, setShowSlide] = useState<boolean>(true);
  const [slideLeft, setSlideLeft] = useState<number>();
  const [slideWidth, setSlideWidth] = useState<number>();
  // Location detail
  const { pathname } = useLocation();
  // Current active nav
  let activeNav: typeof routes[number];
  if (pathname === '/' || routes[0].children!.filter(route => pathname.startsWith(route))[0]) {
    activeNav = routes[0];
  } else {
    activeNav = routes.slice(1).filter(({ path }) => pathname.startsWith(path))[0];
  }
  
  // Change the style of slidebar while pathname changed
  useEffect(() =>{
    setShowSlide(!!activeNav);
    if (activeNav) {
      setShowSlide(true);
      for (const child of navList.current!.children) {
        if (child.nodeName === 'LI') {
          const path = (child as HTMLLIElement).dataset.path;
          if (path === activeNav.path) {
            const currentNode = (child as HTMLLIElement);
            setSlideLeft(currentNode.offsetLeft);
            setSlideWidth(currentNode.offsetWidth);
          }
        }
      }
    }
  }, [pathname]);

  return (
    <div className='navbar'>
      <img className='logo' src={ logo } alt="全栈圈" />
      <ul className='routes' ref={ navList }>
        {
          routes.map(({ path, title }) =>
            <li
              key={ path }
              data-path={ path }
              className='route-item'
            >
              <Link to={ path }>{ title }</Link>
            </li>
          )
        }
        { showSlide && <div className='slide-bar' style={{ left: slideLeft, width: slideWidth }}></div> }
      </ul>
      <TextField label="探索全栈圈" size='small' />
      <div className='personal'>
        {/* 登录前后展示的内容不同 */}
        <Button variant="outlined">登录</Button>
      </div>
    </div>
  );
};

export default Navbar;
